import { defineStore } from 'pinia';
import {
  getUserInfo,
  login as userLogin,
  logout as userLogout,
} from '@/api/user';
import { clearToken, setToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { LoginData } from '@/api/user/types';
import { UserState } from './types';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    gender: undefined,
    address: undefined,
    email: undefined,
    avatar: undefined,
    nickName: undefined,
    permission: [],
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        // TODO: 实现角色切换逻辑
        resolve(null);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // 清空state内容
    resetInfo() {
      this.$reset();
    },

    // 获取用户详细信息
    async info() {
      const res = await getUserInfo();
      this.setInfo(res.data);
    },

    // 登录
    async login(loginForm: LoginData) {
      try {
        await userLogin(loginForm).then(async (res) => {
          setToken(res.data.accessToken);
          // 获取用户详情信息
          await this.info();
          // 查询菜单列表
        });
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    // 退出登录回调
    logoutCallBack() {
      // 清除用户信息
      this.resetInfo();
      // 清除菜单列表
      const appStore = useAppStore();
      appStore.clearServerMenu();
      // 清除token
      clearToken();
      removeRouteListener();
    },
    // 退出登录
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
  persist: {
    key: 'user',
    storage: localStorage,
  },
});

export default useUserStore;
